import { ref, computed } from 'vue'
import { useUserStore } from '../store/user'
import { usePermissionStore } from '../store/permission'
import { useRoleStore } from '../store/role'
import { ElMessage } from 'element-plus'
import { authCenterApi } from '../api/authCenter'

// 使用单例模式缓存Promise
const requestCache = {
  profile: null as Promise<any> | null
}

/**
 * 用户资料相关的组合式函数
 * @returns 用户资料相关的状态和方法
 */
export function useUserProfile() {
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()
  const roleStore = useRoleStore()
  
  const loading = ref(false)
  const error = ref<Error | null>(null)
  
  // 用户信息
  const userInfo = computed(() => userStore.getUserInfo)
  
  // 用户是否已登录
  const isLoggedIn = computed(() => userStore.isLoggedIn)
  
  /**
   * 获取用户资料
   */
  const fetchUserProfile = async () => {
    // 如果已有请求进行中，直接返回缓存的Promise
    if (requestCache.profile) return requestCache.profile
    
    loading.value = true
    error.value = null
    
    // 创建新Promise并缓存
    requestCache.profile = (async () => {
      try {
        // 获取用户信息
        const response = await authCenterApi.getProfile()
        
        if (response.code === 200 && response.data) {
          // 获取角色信息
          const roleObjects = response.data.roles || []
          const roleCodes = roleObjects.map((r: any) => r.code)
          
          // 根据用户名推断角色 - 开发环境使用
          const roleMap = {
            'admin': { code: 'ADMIN', name: '管理员' },
            'teacher': { code: 'TEACHER', name: '教师' },
            'student': { code: 'STUDENT', name: '学生' },
          }
          
          // 用户名映射角色
          const username = response.data.username
          const defaultRole = { code: 'USER', name: '普通用户' }
          
          // 合并角色信息，确保不重复
          const mergedRoleObjects = [...roleObjects]
          const mergedRoleCodes = [...roleCodes]
          
          // 添加默认角色
          if (!mergedRoleCodes.includes(defaultRole.code)) {
            mergedRoleCodes.push(defaultRole.code)
            mergedRoleObjects.push(defaultRole)
          }
          
          // 根据用户名添加特定角色
          const mappedRole = roleMap[username as keyof typeof roleMap]
          if (mappedRole && !mergedRoleCodes.includes(mappedRole.code)) {
            mergedRoleCodes.push(mappedRole.code)
            mergedRoleObjects.push(mappedRole)
          }
          
          console.log('[UserProfile] 用户角色:', mergedRoleCodes)
          
          // 设置用户信息
          userStore.setUserInfo({
            userId: String(response.data.id),
            username: response.data.username,
            email: response.data.email,
            roles: mergedRoleCodes,
            roleObjects: mergedRoleObjects,
            permissions: [],
            avatar: 'https://via.placeholder.com/150',
            lastActive: new Date().toISOString()
          })
        }
        
        // 加载角色枚举
        await roleStore.loadRoleEnums()
        
        // 加载权限
        const permissionResult = await permissionStore.loadPermissions()
        
        return {
          userInfo: userStore.getUserInfo,
          permissions: permissionResult?.permissions || [],
          menuTree: permissionResult?.menuTree || []
        }
      } catch (err: any) {
        console.error('获取用户资料失败:', err)
        error.value = err
        ElMessage.error('获取用户资料失败，请刷新页面重试')
        throw err
      } finally {
        loading.value = false
        requestCache.profile = null
      }
    })()
    
    return requestCache.profile
  }
  
  /**
   * 退出登录
   */
  const logout = async () => {
    try {
      userStore.logout()
      permissionStore.clearPermissions()
      requestCache.profile = null
      return true
    } catch (err) {
      console.error('退出登录失败:', err)
      return false
    }
  }
  
  return {
    userInfo,
    isLoggedIn,
    loading,
    error,
    fetchUserProfile,
    logout
  }
} 